<template>
  <basic-modal v-bind="$attrs" show-confirm @confirm="handleConfirm">
    <n-form-item label="序列号">
      <n-input
        placeholder="请输入序列号"
        clearable
        v-model:value="ownCartItem.imei"
      >
        <template #suffix>
          <n-button quaternary circle>
            <template #icon>
              <n-icon :component="Copy" />
            </template>
          </n-button>
        </template>
      </n-input>
    </n-form-item>
    <n-spin :show="calculateLoading">
      <n-space vertical>
        <div class="select-title">
          <span>问题清单</span>
        </div>
        <div
          class="question-item"
          v-for="question in questionsList"
          :key="question.id"
          :class="{
            'question-item--active': isSelected(question.id),
          }"
          @click.stop="handleSelectQuestion(question.id)"
        >
          <span class="font-bold leading-[28px]"> {{ question.name }} </span>
          <n-icon
            size="24"
            :color="CommonConfig.primaryColor"
            v-show="isSelected(question.id)"
          >
            <CheckmarkCircleSharp />
          </n-icon>
        </div>
        <div class="flex items-center justify-between mt-2">
          <span>回收价格:</span>
          <span class="font-bold">{{ currencyFormat(shownTradeinPrice) }}</span>
        </div>
      </n-space>
    </n-spin>
  </basic-modal>
</template>
<script setup lang="ts">
import { ref, useAttrs, watch, computed } from "vue";
import { currencyFormat } from "@/common/utils/currencyFormatter/index.ts";
import CommonConfig from "@/config/uiTheme/common";
import { Copy, CheckmarkCircleSharp } from "@vicons/ionicons5";
import { isEmpty, cloneDeep, get, debounce } from "lodash-es";
import { calculatePrice } from "@/api/tradein/tradein.api";
import { ICartItemDetailProps } from "./props";
import { TradeInForm } from "@/views/tradeIn/index/data";

const $emits = defineEmits(["confirm"]);

const $attrs = useAttrs();
const props = defineProps<ICartItemDetailProps>();

const calculateLoading = ref<boolean>(false);
const ownCartItem = ref<TradeInForm>({} as TradeInForm);

watch([() => props.cartItem, () => $attrs.show], ([cartItem, show]) => {
  if (show && !isEmpty(cartItem)) {
    console.log(cartItem);
    ownCartItem.value = cloneDeep(cartItem);
  }
});

const questionsList = computed(() => {
  const questionsList = get(ownCartItem.value, "checkList.questionItems") || [];
  return questionsList;
});

const shownTradeinPrice = computed(() => {
  return get(ownCartItem.value, "shownTradeinPrice");
});

const handleSelectQuestion = debounce(function (questionId: string) {
  let selectedChcekMap = get(ownCartItem.value, "selectedChcekMap") || {};
  if (selectedChcekMap[questionId] === "0") {
    selectedChcekMap[questionId] = "1";
  } else {
    selectedChcekMap[questionId] = "0";
  }

  console.log(ownCartItem.value.selectedChcekMap);
  handleCalculatePrice();
}, 500);

const isSelected = (questionId: string) => {
  const selectedChcekMap = get(ownCartItem.value, "selectedChcekMap") || {};
  return selectedChcekMap[questionId] === "1";
};

const handleCalculatePrice = async () => {
  calculateLoading.value = true;
  try {
    let _selectedQuestionIds: string[] = [];
    const selectedChcekMap = get(ownCartItem.value, "selectedChcekMap") || {};
    const variantId = get(ownCartItem.value, "variant.id") || "";
    for (const key in selectedChcekMap) {
      if (selectedChcekMap[key] && selectedChcekMap[key] === "1") {
        _selectedQuestionIds.push(key);
      }
    }
    if (!_selectedQuestionIds.length) {
      // 没有选中问题，显示推荐价格
      ownCartItem.value.shownTradeinPrice = get(
        ownCartItem.value,
        "variant.recTradeinPrice"
      );
      ownCartItem.value.customerPrice = get(
        ownCartItem.value,
        "variant.recTradeinPrice"
      );
      return;
    }
    const params = {
      variantId: variantId,
      selectedQuestionIds: _selectedQuestionIds,
    };
    const res = await calculatePrice(params);
    console.log(res);
    ownCartItem.value.shownTradeinPrice = get(res, "result") || 0;
    ownCartItem.value.customerPrice = get(res, "result") || 0;
  } finally {
    calculateLoading.value = false;
  }
};

const handleConfirm = () => {
  $emits("confirm", ownCartItem.value);
};
</script>
<style lang="scss" scoped>
.question-item {
  @apply w-full border border-transparent rounded-lg  p-3 relative flex  items-center justify-between text-ellipsis overflow-hidden bg-slate-100 cursor-pointer hover:border-theme-main-color;

  &--active {
    @apply border-theme-main-color;
  }
}
</style>
